let layerIndex;
let $;
var toast;
/**
 * 弹出课程新增对话框
 */
function showCourseDlg(id){
    let title="新增课程"
    $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    if (id){

        title="编辑课程"
        $("#formId").css("display","block");
        $.ajax({
            url:"/api/course/"+id,
            method: "GET"
        }).done(result=>{
            console.log(result)
            if (result.code>=0){
                let data=result.data

                $.each(data,function (key,value) {
                    var field = $('#courseForm [name="'+key+'"]');
                    if(field.is(':radio')){
                        field.filter('[value="'+value+'"]').prop('checked',true);
                    }else if(field.is(':checkbox')){
                        field.prop('checked',value==="yes");
                    }else{
                        field.val(value);
                    }
                });
                layui.form.render();
            }else{
                toast.error({
                    message: result.msg,
                });
            }

        })
    }else{
        $("#courseForm")[0].reset();
        $("#formId").css("display","none");
    }
    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px','auto'],
        content: $('#popDlg').prop("innerHTML")
    });
}
function getSearchCondition(){
    let formData={}
    $('#queryForm').find('input,select').each(function(){
        let name=$(this).attr('name');
        let value=$(this).val();
        if(name&&value){
            formData[name]=value;
        }
    });
    return formData;
}
layui.use(function (){
    $=layui.$
    toast =layui.toast

    layui.form.on('submit(course-dlg)', function(data) {
        event.preventDefault();
//        commitStudentDlg();
        if(this.isSubmitting) return false;
        this.isSubmitting =true;
        commitCourseDlg().catch(error=>{
            console.error("提交失败：",error);
        }).finally(()=>{
            this.isSubmitting =false;
        });
        return  false;
    })


    const table=layui.table;
    let course=getSearchCondition();
    table.render({
        elem:'#tbCourse',
        url:'/api/course/getbypage',
        //此处为静态模拟数据，实际使用时需换成真实接口
        method:"POST",
        contentType:'application/json',
        where:{"data":course},
        page:true,
        cols:[[
            {type: 'checkbox',fixed:'left'},
            {field: 'id',fixed: 'left',width:80,title:'id',sort:true},
            {field: 'cno',title: '课程号'},
            {field: 'cname',title: '课程名',width: 150},
            {field: 'right',title: '操作',width: 134,minwidth:125,templet:'#editTemplate'}
        ]],
        done:function (rs){
            //console.log(rs)
        }
    });
    //触发单元格工具事件
    table.on('tool(tbCourse)',function (obj){
        var data =obj.data;
        if(obj.event==='edit'){
            $("#btnOk").prop("disabled",false).removeClass("layui-btn-disabled");
            showCourseDlg(data.id);
            //数据填充表单
            $.each(data,function(key,value){
                var field=$('#courseForm [name="' + key + '"]');
                if(field.is(':radio')){
                    field.filter('[value="'+value+'"]').prop('checked',true);
                    //选中对应的单选按钮
                }
                else if(field.is(':checkbox')){
                    field.prop('checked',value ==="yes");//选中复选框
                }
                else{
                    field.val(value);//填充文本框或其他字段
                }
            });

//            layerIndex=layer.open({
//                title:'编辑 - id:'+data.id,
//                type:1,
//                area:['80%','80%'],
//                content:$("#studentForm")
//            });
        }
    })
});
function search(){
    let course=getSearchCondition();
    const table=layui.table;
    table.reloadData("tbCourse",{
        where: {data:course}
    });
    console.log("where condition:"+JSON.stringify(course))
}
function deleteConfirm(){
    const table=layui.table;
    //获取表格的选中状态
    const checkStatus=table.checkStatus('tbCourse');
    console.log(checkStatus.data);
    const ids=checkStatus.data.map(item=>item.id);
    if(ids.length===0){
        layer.msg('请选择要删除的课程!',{icon:2});
        return;
    }
    layer.confirm('是否删除？一旦删除，不可恢复',{icon:3},function () {
        $.ajax({
            url:"/api/course/deleteId/"+ids.join(","),
            method:"DELETE",
        }).done(result=>{
            search();
        })
        layer.closeAll();//关闭所有层
    },function (){
    });
}
function commitCourseDlg(){
    return new Promise((resolve, reject) => {
        $("#btnOK").prop("disabled",true).addClass("layui-btn-disabled");
        const id = $("#id").val();
        const formData = $(".layui-layer-page #courseForm").serialize();
        const url = id ? "/api/course/update": "/api/course/add";
        const method = id ? "PUT":"POST";
        $.ajax({
            url:url,
            method:method,
            data:formData
        }).done(result=>{
            if(result.code>=0 && result.data?.id){
                search();
                if (layerIndex){
                    layer.close(layerIndex);
                }
                resolve(result);
            }else{
                const errorMsg =result.msg || (id?"更新失败":"新增失败，没有返回id");
                toast.error({message:errorMsg});
                reject(new Error(errorMsg));
            }
        }).fail((jqXHR, textStatus, errorThrown)=>{
            const errorMsg = '请求失败：${textStatus}- ${errorThrown}';
            console.error(errorMsg);
            alert("系统错误，请稍后重试");
            reject(new Error(errorMsg));
        }).always(()=>{
            $("#btnOK").prop("disable",false).removeClass("layui-btn-disabled");
        });
    });
}